package top.resty.erp.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.resty.erp.domain.Brand;
import top.resty.erp.service.BrandService;
import top.resty.erp.util.LayuiJson;

import java.util.List;

/**
 * <pre>
 *
 * </pre>
 *
 * @author : resty
 * @date : 2021年03月21 16:47
 */
@Controller
@RequestMapping("/brand")
public class BrandController {
	
	@Autowired
	private BrandService brandService;
	
	@RequestMapping("/all")
	@ResponseBody
	public List<Brand> getAllBrands(){
		return brandService.getAllBrands();
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public String saveBrand(String name){
		if (brandService.saveBrand(name)) {
			return "成功";
		}
		return "失败";
	}
	
	
	
	@RequestMapping("/del")
	@ResponseBody
	public String brandDelete(int id){
		if(brandService.delete(id)){
			return "success";
		}
		return "";
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public String brandUpdate(String keyStr,String valueStr,int id){
		boolean boo = false;
		try {
			boo = brandService.updateBrand(keyStr, valueStr, id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(boo){
			return "成功";
		}
		return "失败";
	}
	
	@RequestMapping("/brandList")
	@ResponseBody
	public LayuiJson<Brand> getBrands(String searchName ,int page,int limit){
		System.out.println(searchName);
		
		//通过mybatis helper插件实现分页信息的封装.
		Page<Object> objects = PageHelper.startPage(page,limit);
		//通过插件实现查询对应的结果.
		List<Brand> brands = brandService.getBrands(searchName);
		//将结果封装进 自定义的Table封装类.
		LayuiJson<Brand> brandLayuiJson = new LayuiJson<Brand>();
		// 设置封装类的属性
		brandLayuiJson.setCount((int) objects.getTotal());
		brandLayuiJson.setData(brands);
		// 返回封装好的Table 对象.
		return brandLayuiJson;
	}
	
	
	@RequestMapping("/list")
	public String goToBrandsPage(Model model) {
		List<Brand> allBrands = brandService.getAllBrands();
		model.addAttribute("brands", allBrands);
		
		return "man/brand";
	}
	
}
